package pers.mihao.quickstream.common.util;

import org.springframework.util.ObjectUtils;
import pers.mihao.quickstream.common.constans.CodeEnum;

import java.lang.reflect.Method;

public class EnumUtil {

    public static <T extends Enum<T>> T valueOfOrDef(Class<T> enumType, String type, T defaultEnum) {
        if (StringUtil.isBlack(type)) {
            return defaultEnum;
        }
        return valueOf(enumType, type);
    }

    public static <T extends CodeEnum> T getEnumByCode(Class<T> enumClazz, Integer code) {
        if (enumClazz == null) {
            throw new IllegalArgumentException("enumClazz参数不能为空.");
        } else if (!CodeEnum.class.isAssignableFrom(enumClazz)) {
            throw new IllegalArgumentException("enumClazz未实现CodeEnum接口.");
        } else {
            try {
                Method m = enumClazz.getMethod("values");
                CodeEnum[] ies = (CodeEnum[]) m.invoke(null);
                CodeEnum[] arr$ = ies;
                int len$ = ies.length;
                for (int i$ = 0; i$ < len$; ++i$) {
                    CodeEnum ie = arr$[i$];
                    if (ObjectUtils.nullSafeEquals(ie.getCode(), code)) {
                        return (T) ie;
                    }
                }
                return null;
            } catch (Exception var8) {
                throw new RuntimeException(var8);
            }
        }
    }

    /**
     * 将String 转成存在的枚举类型
     *
     * @param enumType
     * @param type
     * @param <T>
     * @return
     */
    public static <T extends Enum<T>> T valueOf(Class<T> enumType, String type) {
        // 1.将type 转成大写
        char[] types = type.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (char c : types) {
            if ('a' <= c && c <= 'z') {
                sb.append(Character.toUpperCase(c));
            } else if ('A' <= c && c <= 'Z') {
                sb.append("_").append(c);
            } else {
                sb.append(c);
            }
        }
        return Enum.valueOf(enumType, sb.toString());
    }
}
